package com.dailyblue.javaee.controller;

import com.dailyblue.javaee.bean.User;
import com.dailyblue.javaee.service.UserService;
import com.dailyblue.javaee.service.impl.UserServiceImpl;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet("/user_cookie_login")
public class UserLoginCookieController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        UserService service = new UserServiceImpl();
        User user = service.login(name, password);
        if (user == null) {
            response.sendRedirect("cookie/login.jsp?error=1");
            return;
        }
        // 保存到客户端电脑 cookie
        // 产生cookie对象
        Cookie cookie = new Cookie("USER", user.getName());
        // 设置存活时间 如果不设置，临时存放
        cookie.setMaxAge(60 * 60 * 24);
        // 存放到浏览器的硬盘中
        response.addCookie(cookie);
        response.sendRedirect("cookie/index.jsp");
    }
}